<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import pinia from '/@/stores';
import api from '/@/api/email/index';
import { useEmail } from '/@/stores/email';
import { type FormInstance, type FormRules } from 'element-plus'

defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const ruleFormRef = ref<FormInstance>()
const stores = useEmail(pinia);

// 工厂列表
const factoryOptions = ref<{
    id: number
    name: string
}[]>([])
// 付款方式
interface RuleForm {
    orderId: number | undefined
    factoryId: number | undefined
}
const ruleForm = reactive({
    orderId: undefined,
    factoryId: undefined,
})
const rules = reactive<FormRules<RuleForm>>({
    factoryId: [{ required: true, message: '请选择工厂供应商', trigger: 'change' }],
})
// 查询工厂数据
const getFactoryList = async () => {
    const account = stores.curAccount;
    try {
        const { data } = await api.factory.getList({
            emailAccount: account,
            pageNum: 1,
            pageSize: 999,
        });
        factoryOptions.value = data;
    } catch (error) {
        console.log(error)
    }
};
const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const obj: RuleForm = { ...ruleForm }
            const { code } = await api.order.settlePayment(obj)
                if (code === 200) {
                    ElMessage.success('结清成功')
                    emit('refresh')
                    close()
                }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const close = () => {
    ruleFormRef.value?.resetFields()
    emit('update:modelValue', false)
}

defineExpose({
    ruleForm
})

onMounted(() => {
    getFactoryList()
})
</script>
<template>
    <TwoDialog id="settleFinalPayMent" :modelValue="modelValue" title="结清尾款" width="520px" @submit="submit(ruleFormRef)" @close="close" @minimize="emit('update:modelValue', false)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-row :gutter="16">
                <el-col :span="24">
                    <el-form-item label="工厂供应商" prop="factoryId">
                        <el-select v-model="ruleForm.factoryId" placeholder="请选择">
                            <el-option v-for="fa in factoryOptions" :label="fa.name" :value="fa.id" :key="fa.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </TwoDialog>
</template>
<style lang="scss" scoped>
.cascader-panel {
    width: fit-content;
}
</style>